package org.example.leetCode.simple;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class LongestCommonPrefix_0014 {

    public static void main(String[] args) {
        LongestCommonPrefix_0014 test = new LongestCommonPrefix_0014();
        String[] arr = new String[]{"flower","flow","flight"};
        System.out.println(test.longestCommonPrefix(arr));
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }
        int lastCommonIndex = strs[0].length();
        for (int i = 1; i < strs.length; i++) {
            lastCommonIndex = getLastComonIndex(strs[i - 1], strs[i], lastCommonIndex);
        }
        return strs[0].substring(0, lastCommonIndex);
    }

    int getLastComonIndex(String str1, String str2, int lastNum) {
        int length = Math.min(str1.length(), str2.length());
        for (int i = 0; i < length; i++) {
            if (str1.charAt(i) != str2.charAt(i)) {
                return Math.min(i, lastNum);
            }
        }
        return Math.min(length, lastNum);
    }
}
